﻿using System.Collections.Generic;

namespace HCore
{
    public abstract class GoalComposite<T> : Goal<T>
    {
        protected readonly LinkedList<Goal<T>> _subGoalList;

        public GoalComposite(T owner, int goalType) : base(owner, goalType)
        {
            _subGoalList = new LinkedList<Goal<T>>();
        }

        protected GoalStatus ProcessSubgoals()
        {
            while (_subGoalList.Count > 0 &&
                   (_subGoalList.First.Value.isComplete() || _subGoalList.First.Value.hasFailed()))
            {
                _subGoalList.First.Value.Terminate();
                _subGoalList.RemoveFirst();
            }

            if (_subGoalList.Count > 0)
            {
                GoalStatus StatusOfSubGoals = _subGoalList.First.Value.Process();
                if (StatusOfSubGoals == GoalStatus.Completed && _subGoalList.Count > 1)
                {
                    return GoalStatus.Active;
                }

                return StatusOfSubGoals;
            }

            return GoalStatus.Completed;
        }

        protected bool ForwardMessageToFrontMostSubgoal(Telegram msg)
        {
            if (_subGoalList.Count > 0)
            {
                return _subGoalList.First.Value.HandleMessage(msg);
            }

            return false;
        }

        public override bool HandleMessage(Telegram msg)
        {
            return ForwardMessageToFrontMostSubgoal(msg);
        }

        public void AddSubgoal(Goal<T> goal)
        {
            _subGoalList.AddFirst(goal);
        }

        public void RemoveAllSubgoals()
        {
            foreach (Goal<T> s in _subGoalList)
            {
                s.Terminate();
            }

            _subGoalList.Clear();
        }
    }
}